package com.trade.training.common.validator;

import com.trade.training.common.exception.CustomException;
import com.trade.training.config.ErrorCode;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验工具类
 *
 * @author herry-zhang
 * @date 2018-7-24 15:27:34
 */
public class ValidatorUtils {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws CustomException 校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                msg.append(constraint.getMessage()).append("，");
            }
            throw new CustomException(ErrorCode.SYSTEM_ARGUMENT_ERROR.getCode(), msg.toString().replaceAll("，$", ""));
        }
    }
}
